<?php

// +----------------------------------------------------------------------
// | Api接口公共控制器
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\api\v3;

use app\common\model\Area as AreaModel;
use app\middleware\api\Auth;
use app\common\controller\Base;
use app\model\app\Version as VersionModel;
use app\model\ucenter\User as UserModel;
use app\event\ucenter\User as UserEvent;
use think\Config;
use think\Exception;
use think\facade\Log;
use think\Response;

class Common extends Base
{
    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;
    protected $data;
    /**
     * 当前访问用户
     * @var null|UserModel
     */
    protected $user = null;
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;


    protected $middleware = [
//        UserLogin::class,
        Auth::class
    ];

    /**
     * 来自的平台
     */
    protected $platform = 'android';
    protected $app_version = '0.0.0';
    protected $wgt_version = '0.0.0';
    protected $is_examine = 1;
    /**
     * @var VersionModel
     */
    protected $version_info;
    protected $version_channel;
    /**
     * 架构函数
     */
    protected function initialize()
    {
        if ($this->request->isOptions()) {
            abort(200, '通过');
        }
        parent::initialize();
        $this->app = app();
        $this->request = $this->app['request'];
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
//        $lng = $this->request->request('lng',120.43719);
//        $lat = $this->request->request('lat',41.59264);
        $this->platform  = $this->request->header('platform');
        $this->app_version  = $this->request->header('app_version');
        $this->wgt_version  = $this->request->header('wgt_version');
        $this->version_channel  = $this->request->header('app_channel');

        $this->version_info =  VersionModel::where('status', 1)->where('version_code',$this->request->param('version_code',''))->find();

//        if ($this->app_version != '3.0.0')
//        {
//            $this->is_examine = 0;
//        }

        //配置信息
        //如果非服务端中转模式需要修改为中转
//        if ($lat && $lng)
//        {
//            $this->request->area = AreaModel::field('ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$lat.'*PI()/180-lat*PI()/180)/2),2)+COS(22.299439*PI()/180)*COS(lat*PI()/180)*POW(SIN(('.$lng.'*PI()/180-lng*PI()/180)/2),2)))*1000) as distance ,id,shortname,lng,lat')
//                ->order('distance ASC')
//                ->find();
//        }

        $this->is_examine = 0;
//			$this->registerMiddleware();
        if ($this->request->user)
        {
            $this->user = $this->request->user;

            if ($this->user['id'] == 47)
            {
                $this->is_examine = 1;
            }

            if (!$this->user['pid'])
            {
                $this->is_examine = 1;
            }
            if ($this->user['id'] == 16006)
            {
                $this->is_examine = 0;
            }
            if ($this->user['id'] == 16536)
            {
                $this->is_examine = 0;
            }
        }else{
            if ($this->request->ip() == '127.0.0.1')
            {
                $this->user = UserEvent::getInfoByToken('a4db8770d7b7cef9e1f48dc705cd60dc')['data'];
            }
        }
        if ($this->app_version == '3.1.12')
        {
            $this->is_examine = 0;
        }

//            dump($this->user);exit();
//			$this->validateName = $this->dbname;
//			$name = '\app\\' .request()->auth_module . '\event\\' . $this->dbname;
//			if (class_exists($name)) {
//				$this->event = new $name;
//			}
//            import('yicmf.SymmetricEncryption',EXTEND_PATH);
//            $sy = new \SymmetricEncryption();
//            if ($sy->decrypt('zboss_token', $this->request->header('token')))
//            {
//                $this->is_pass = true;
//            }
    }
//
//		/**
//		 * 空操作，调用对应方法
//		 * @author 微尘 <yicmf@qq.com>
//		 * @datetime: 2020/6/30 11:33
//		 */
//		public function _empty()
//		{
//
//			$re = $this->request->param(false);
//
//			$action = $this->request->action(true);
//			if (!empty($this->openEvent) &&
//				(in_array($action, $this->openEvent) || in_array($action, array_keys($this->openEvent)))
//			) {
//				try {
//					$keys = array_keys($this->openEvent);
//					foreach ($keys as $index => $key) {
//						if (!$key) {
//							unset($keys[$index]);
//						}
//					}
//					if (in_array($action, $keys)) {
//						$method = $this->openEvent[$action];
//						if ($this->request->isGet() && isset($method['get'])) {
//							throw new Exception($method['get']);
//						}
//						if ($this->request->isPost() && isset($method['post'])) {
//							throw new Exception($method['post']);
//						}
//						if (isset($method['action'])) {
//							$action = $method['action'];
//						}
//						if (isset($method['event'])) {
//							$this->event = new $method['event'];
//						}
//						if (isset($method['validateName'])) {
//							$this->validateName = $method['validateName'];
//						}
//					}
//					if ($this->request->isPost() && $this->validateName) {
//						$result = $this->validate($this->request->post(), $this->validateName);
//						if ($result !== true) {
//							throw new Exception('数据验证错误，【' . $result . '】');
//						}
//					}
//					$data = $this->event->$action($this->request->param(false), $this->user);
//				} catch (\Exception $e) {
//					$data['code'] = 1;
//					$data['message'] = $e->getMessage();
//				}
//			} else {
//				$data['code'] = 1;
//				$data['message'] = '当前操作未定义';
//			}
//			return json($data);
//		}
//

    /**
     * 返回ajax请求数据
     * @param array $data
     * @return Response
     */
    protected function autoAjax(array $data): Response
    {
        if ($data['code'] == 0) {
            return $this->successAjax(isset($data['data'])?$data['data']:null, $data['message'] ?? null);
        } else {
            return $this->errorAjax($data['message'],$data['code']);
        }
    }

    /**
     * 返回ajax请求数据
     * @param array|string|null $data
     * @param string|null $message
     * @param int $code
     * @return Response
     */
    protected function successAjax($data, ?string $message = 'success', int $code = 0): Response
    {
        $result['data'] = $data;
        $result['code'] = $code;
        $result['message'] = $message;
        return response_ajax($result);
    }

    /**
     * 返回ajax请求数据
     * @param string|array $message
     * @param int $code
     * @return Response
     */
    protected function errorAjax($message = '请求错误', int $code = 1): Response
    {
        $result['code'] = $code;
        $result['message'] = $message;
        return response_ajax($result);
    }

}
